package com.amar.dtadmin.apidoc.util;

import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiEnumConstant;
import com.intellij.psi.PsiExpression;
import com.intellij.psi.PsiField;
import com.intellij.psi.PsiPrimitiveType;
import com.intellij.psi.PsiReference;
import com.intellij.psi.PsiType;
import com.intellij.psi.impl.JavaConstantExpressionEvaluator;
import com.intellij.psi.util.PsiTypesUtil;

/**
 * @author xiaoshiqiang
 * @since 2025/2/8
 */
public class PsiFieldUtils {
    public static String getFieldDeclaredValue(PsiField field) {
        PsiExpression initializer = field.getInitializer();
        if (initializer == null) {
            return null;
        } else {
            PsiReference reference = initializer.getReference();
            if (reference == null) {
                Object constant = JavaConstantExpressionEvaluator.computeConstantExpression(initializer, false);
                return constant == null ? null : constant.toString();
            } else {
                PsiElement resolve = reference.resolve();
                if (resolve instanceof PsiEnumConstant) {
                    return ((PsiEnumConstant) resolve).getName();
                } else {
                    return resolve instanceof PsiField ? getFieldDeclaredValue((PsiField) resolve) : null;
                }
            }
        }
    }

    public static String getFieldDefaultValue(PsiField field) {
        PsiExpression initializer = field.getInitializer();
        if (initializer != null) {
            return getFieldDeclaredValue(field);
        } else {
            PsiType fieldType = field.getType();
            String dv = getDefaultValueFromFieldText(field);
            if (dv != null) {
                return dv;
            } else {
                return fieldType instanceof PsiPrimitiveType ? PsiTypesUtil.getDefaultValueOfType(fieldType) : null;
            }
        }
    }

    private static String getDefaultValueFromFieldText(PsiField field) {
        String text = field.getText();
        int nameIdx = text.lastIndexOf(field.getName());
        text = text.substring(nameIdx + field.getName().length());
        int eqIdx = text.lastIndexOf(61);
        if (eqIdx == -1) {
            return null;
        } else {
            String subText = text.substring(eqIdx + 1).trim();
            int beginIdx = 0;
            int endIdx = subText.length();
            if (subText.endsWith(";")) {
                --endIdx;
            }

            if (subText.startsWith("\"")) {
                ++beginIdx;
                --endIdx;
            }

            return subText.substring(beginIdx, endIdx);
        }
    }
}
